# -*-coding:utf-8 -*-
# @Time: 2023/3/15 0015 上午 9:35
# @Author: Cwoner
# @Organization: CTIM
# @Software: PyCharm
# -*-coding:utf-8 -*-
# @Time: 2023/2/20 0020 下午 14:33
# @Author: Cwoner
# @Organization: CTIM
# @Software: PyCharm


import requests
from lxml import etree
import hashlib
from setting import SAVEPATH
import os
import re
import time

from tools.serverAPI import upload_file

class TongLingYouSeJinShu():
    def __init__(self,ccdate,id=''):#20230101
        self.url = f'https://www.cnmn.com.cn/ShowNewsList.aspx?id=48'
        self.ccdate = ccdate
        self.id = id
        self.name = '铜陵有色报'
        print('初始化：',self.name, self.url)
        self.mid = hashlib.md5((self.name+'_baozi').encode()).hexdigest()
        if not os.path.isdir(SAVEPATH+self.mid):
            os.mkdir(SAVEPATH+self.mid)

    def index(self):
        headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Referer": "https://www.yunzhan365.com/homepage/chxf/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
            "sec-ch-ua": "\"Chromium\";v=\"110\", \"Not A(Brand\";v=\"24\", \"Google Chrome\";v=\"110\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        }
        response = requests.get(self.url, headers=headers,timeout=10)
        if response.status_code == 200:
            text = response.content.decode('utf-8')
            html = etree.HTML(text)
            newLIst = []
            newList_page = html.xpath('//div[@id="tab11-1"]//a')
            for bookItem in newList_page:
                try:
                    title = bookItem.xpath('./@title')[0]
                    url = f'https://www.cnmn.com.cn/' + bookItem.xpath('./@href')[0]
                    newLIst.append({'title':title,'url':url})
                except:
                    continue
            return newLIst


    def get_pdf(self,url):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
        }
        response = requests.get(url, headers=headers, verify=False,timeout=10)
        ban_data = []
        if response.status_code == 200:
            text = response.text
            html = etree.HTML(text)
            pdf_node = html.xpath('//div[@id="txtcont"]//a')
            for pdfItem in pdf_node:
                pdf_url = pdfItem.xpath('./@href')[0]
                title = pdfItem.xpath('string(.)')
                ban_data.append({'pdf_url':pdf_url,'title':title})
            return ban_data



    def __download(self,file,url,title,tid,c=0):
        if 'readstep2.html' in url:
            return False
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
        }
        try:
            response = requests.get(url, headers=headers, verify=False,timeout=10)
        except:
            if c > 2:
                return
            return self.__download(file,url,title,tid,c+1)
        if response.status_code == 200:
            path = SAVEPATH + self.mid + '/' + self.ccdate + '/'
            if not os.path.isdir(path):
                os.mkdir(path)
            with open(path + file,'wb',) as f:
                f.write(response.content)
            data = {
                'entity_id': self.mid,
                'title': title,
                'tid': tid,
                'file_name': file,
                'origin_url': url,
                'ndate': self.ccdate[:4] + '-' + self.ccdate[4:6] + '-' + self.ccdate[6:8]
            }
            upload_file(data, response.content)
            return True
        else:
            return False


    def dispatcher(self):
        newLIst = self.index()
        for item in newLIst:
            title = item['title']
            url = item['url']
            ban_data = self.get_pdf(url)
            for item in ban_data:
                ntitle = title + item['title']
                print('找到：',ntitle,item['pdf_url'])
                tid = hashlib.md5((self.name+item['pdf_url']).encode()).hexdigest()
                file = tid + '.pdf'
                stat = self.__download(file,item['pdf_url'],ntitle,tid)


    def run(self):
        self.dispatcher()





if __name__ == '__main__':
    ccdate = '20230305'
    hr = TongLingYouSeJinShu(ccdate)
    hr.run()



